/*
 * @(#) ReflectUtil.java 2011-4-21
 *
 * Copyright (c) 2010, Strong Technology. All Rights Reserved.
 * Strong Technology. CONFIDENTIAL
 */
package cn.strong.gweva.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * 类反射用Util
 * 
 * @author lilanfei
 * @version 1.0
 * @since 2011-4-21
 */
public class ReflectUtil
{
	//日志
	private static final Log logger = LogFactory.getLog(ReflectUtil.class);

	/**
	 * 设置指定属性的值
	 * @param target 目标实例
	 * @param fname 属性名
	 * @param ftype 属性类
	 * @param fvalue 属性值
	 */
	public static void setFieldValue(Object target, String fname, Class<?> ftype, Object fvalue)
	{
		if (target == null || fname == null || "".equals(fname)
				|| (fvalue != null && !ftype.isAssignableFrom(fvalue.getClass())))
		{
			return;
		}
		Class<?> clazz = target.getClass();
		try
		{
			Method method = clazz.getDeclaredMethod("set" + Character.toUpperCase(fname.charAt(0))
					+ fname.substring(1), ftype);
			if (!Modifier.isPublic(method.getModifiers()))
			{
				method.setAccessible(true);
			}
			method.invoke(target, fvalue);

		}
		catch (Exception me)
		{
			if (logger.isDebugEnabled())
			{
				logger.debug(me);
			}
			try
			{
				Field field = clazz.getDeclaredField(fname);
				if (!Modifier.isPublic(field.getModifiers()))
				{
					field.setAccessible(true);
				}
				field.set(target, fvalue);
			}
			catch (Exception fe)
			{
				if (logger.isDebugEnabled())
				{
					logger.debug(fe);
				}
			}
		}
	}
}
